package com.zm.shop.controller;

import com.zm.shop.common.constants.AuthCons;
import com.zm.shop.common.entity.UserEntity;
import com.zm.shop.feign.UserService;
import lombok.extern.slf4j.Slf4j;
import me.zhyd.oauth.config.AuthConfig;
import me.zhyd.oauth.exception.AuthException;
import me.zhyd.oauth.model.AuthCallback;
import me.zhyd.oauth.model.AuthResponse;
import me.zhyd.oauth.model.AuthUser;
import me.zhyd.oauth.request.AuthDingTalkRequest;
import me.zhyd.oauth.request.AuthRequest;
import me.zhyd.oauth.utils.AuthStateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Controller
@Slf4j
@RequestMapping("/auth/oauth")
public class OauthController {

    @Autowired
    private UserService userService;

    @RequestMapping("/login")  //第三方登入
    public void login(HttpServletResponse response) throws IOException {
        log.info("进入render：" );
        //获取第三方接口
        AuthRequest authRequest = getAuthRequest();
        //获取接口授权地址
        String authorizeUrl = authRequest.authorize(AuthStateUtils.createState());
        log.info(authorizeUrl);
        //重定向到授权页面
        response.sendRedirect(authorizeUrl);
    }

    @RequestMapping("/callback")  //第三方登入回调的方法
    public String callback(AuthCallback authCallback, HttpServletRequest request){
        //获取第三方接口
        AuthRequest authRequest=getAuthRequest();
        //第三方登入的响应
        AuthResponse<AuthUser> response = authRequest.login(authCallback);
        if (response.ok()){
            AuthUser data=response.getData();
            //查询是否第一次登入
            UserEntity userEntity=userService.findUser("auth_id",data.getUuid());
            if (userEntity==null){
                userEntity.setUsername(data.getUsername());
                userEntity.setAuthId(data.getUuid());
                //第一次登入注册该账号
                userService.register(userEntity);

            }
            //保存登入信息
            request.getSession().setAttribute(AuthCons.LOGIN_USER,userEntity);
            //成功跳转首页
            return "redirect:http://localhost/home";
        }
        //失败跳转登入页面
        return "redirect:http://localhost/auth/loginUser.html";
    }

    private AuthRequest getAuthRequest() { //获取第三方接口的请求
        AuthRequest authRequest  = new AuthDingTalkRequest(AuthConfig.builder()
                        .clientId("4Dm8L6L5OFiPjoKF8oLOUG9u") //api ID
                        .clientSecret("8dN0bzkYsrMWs1EDABXYv6eTg67GESTh")  //secret ID
                        .redirectUri("http://localhost/auth/oauth/callback")   //回调方法
                        .build());
        if (null == authRequest) {
            throw new AuthException("未获取到有效的Auth配置");
        }
        return authRequest;
    }

}
